<template>
	<div class="game-container report-container">
		<div class="view-container dealer-container">
			<div class="params">
				<el-form
					ref="searchForm"
					:inline="true"
					:model="queryData"
					label-width="auto"
					prop="merchantClientId"
				>
					<el-form-item :label="$t('common.choose_merchant') + ':'">
						<merchant-select
							v-model="queryData.merchantClientId"
							:placeholder="$t('common.please_choose')"
						></merchant-select>
					</el-form-item>
					<el-form-item style="margin-left: 8px">
						<el-button
							type="primary"
							icon="el-icon-search"
							:disabled="loading"
							size="medium"
							@click="loadData"
						>
							{{ $t('common.search') }}
						</el-button>
						<!-- <el-button
							icon="el-icon-refresh-left"
							:disabled="loading"
							size="medium"
							@click="reset"
						>
							重置
						</el-button> -->
						<el-button
							v-if="hasPermission('501051')"
							type="warning"
							icon="el-icon-folder"
							:disabled="loading"
							size="medium"
							@click="addOrEditButton(0)"
						>
							{{ $t('common.add') }}
						</el-button>
					</el-form-item>
				</el-form>
			</div>
			<div class="content">
				<el-table
					v-loading="loading"
					size="mini"
					row-key="id"
					:data="tableData"
					class="small-size-table"
					style="width: 100%;margin-top:20px"
					element-loading-spinner="el-icon-loading"
					:header-cell-style="getRowClass"
				>
					<el-table-column
						prop="activitySort"
						align="center"
						:label="$t('common.sort')"
					></el-table-column>
					<el-table-column
						align="center"
						:label="$t('operation.activity_page')"
					>
						<template slot-scope="scope">
							{{
								scope.row[
									getKey('activityName', {
										map: {
											zh_CN: 'Cn',
											en_US: 'En',
											vi_VN: 'Vn',
											th_TH: 'Th'
										},
										index: 1,
										zh: true
									})
								]
							}}
						</template>
					</el-table-column>
					<el-table-column
						prop="remark"
						align="center"
						:label="$t('common.remark')"
					></el-table-column>
					<el-table-column
						prop="status"
						align="center"
						:label="$t('common.status')"
					>
						<template slot-scope="scope">
							<div
								v-if="scope.row.activityStatus === 0"
								class="disableRgba"
							>
								{{ $t('common.tyz') }}
							</div>
							<div
								v-else-if="scope.row.activityStatus === 1"
								class="normalRgba"
							>
								{{ $t('common.status_turn_on') }}
							</div>
							<span v-else>-</span>
						</template>
					</el-table-column>

					<el-table-column
						prop="createdBy"
						align="center"
						:label="$t('common.createBy')"
					></el-table-column>
					<el-table-column
						prop="createdAt"
						align="center"
						:label="$t('common.createAt')"
					></el-table-column>

					<el-table-column
						prop="updatedBy"
						align="center"
						:label="$t('common.last_updateBy')"
					></el-table-column>
					<el-table-column
						prop="updatedAt"
						align="center"
						:label="$t('common.last_updateAt')"
					></el-table-column>
					<el-table-column
						align="center"
						:label="$t('common.actions')"
						width="220px"
					>
						<template slot-scope="scope">
							<el-button
								v-if="hasPermission('501052')"
								:disabled="loading"
								:type="
									scope.row.activityStatus === 0
										? 'success'
										: 'danger'
								"
								size="medium"
								class="noicon"
								@click="changeSwitch(scope.row)"
							>
								{{
									scope.row.activityStatus === 0
										? $t('common.start_up')
										: $t('common.stop_use')
								}}
							</el-button>
							<el-button
								v-if="hasPermission('501053')"
								type="primary"
								icon="el-icon-edit"
								size="medium"
								:disabled="scope.row.activityStatus === 1"
								@click="addOrEditButton(1, scope.row)"
							>
								{{ $t('common.edit') }}
							</el-button>
							<el-button
								v-if="hasPermission('501054')"
								:disabled="scope.row.activityStatus === 1"
								type="danger"
								icon="el-icon-delete"
								size="medium"
								@click="deleteButton(scope.row)"
							>
								{{ $t('common.delete') }}
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<el-pagination
					v-show="!!total"
					:current-page.sync="pageNum"
					class="pageValue"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="pageSize"
					:page-sizes="pageSizes"
					:total="total"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination>
			</div>
			<el-dialog
				:title="addOrEdit === 0 ? $t('common.add') : $t('common.edit')"
				:visible.sync="dialogVisible"
				:width="$i18n.locale === 'zh_CN' ? `520px` : `700px`"
				class="dialogStyle"
				@close="onDialogClose"
			>
				<el-divider></el-divider>
				<el-form
					ref="dialogForm"
					:model="dialogData"
					label-width="auto"
				>
					<el-form-item
						:label="$t('common.choose_merchant') + ':'"
						prop="merchantId"
						:rules="[
							{
								required: true,
								message: $t('common.please_choose'),
								trigger: 'change'
							}
						]"
					>
						<merchant-select
							v-model="dialogData.merchantId"
							:disabled="!!rowData"
							:merchantInfo.sync="merchantInfoA"
							:placeholder="$t('common.please_choose')"
							@change="handleMerchantIdChange"
						></merchant-select>
					</el-form-item>
					<el-form-item
						v-if="filterLanguages('zh_CN')"
						:label="
							`${$t('operation.activity_page')}-${$t(
								'common.zh'
							)}:`
						"
						prop="activityNameCn"
						:rules="[
							{
								required: true,
								message: $t('common.please_enter'),
								trigger: 'blur'
							}
						]"
					>
						<el-input
							v-model="dialogData.activityNameCn"
							:placeholder="
								$t(
									'operation.promotion_page_config.input_tips1'
								)
							"
							autocomplete="off"
						></el-input>
					</el-form-item>
					<el-form-item
						v-if="filterLanguages('en_US')"
						:label="
							`${$t('operation.activity_page')}-${$t(
								'common.en'
							)}:`
						"
						prop="activityNameEn"
						:rules="[
							{
								required: true,
								message: $t('common.please_enter'),
								trigger: 'blur'
							}
						]"
					>
						<el-input
							v-model="dialogData.activityNameEn"
							:placeholder="
								$t(
									'operation.promotion_page_config.input_tips2'
								)
							"
							autocomplete="off"
						></el-input>
					</el-form-item>
					<el-form-item
						v-if="filterLanguages('th_TH')"
						:label="
							`${$t('operation.activity_page')}-${$t(
								'common.th'
							)}:`
						"
						prop="activityNameTh"
						:rules="[
							{
								required: true,
								message: $t('common.please_enter'),
								trigger: 'blur'
							}
						]"
					>
						<el-input
							v-model="dialogData.activityNameTh"
							:placeholder="
								$t(
									'operation.promotion_page_config.input_tips3'
								)
							"
							autocomplete="off"
						></el-input>
					</el-form-item>
					<el-form-item
						v-if="filterLanguages('vi_VN')"
						:label="
							`${$t('operation.activity_page')}-${$t(
								'common.vn'
							)}:`
						"
						prop="activityNameVn"
						:rules="[
							{
								required: true,
								message: $t('common.please_enter'),
								trigger: 'blur'
							}
						]"
					>
						<el-input
							v-model="dialogData.activityNameVn"
							:placeholder="
								$t(
									'operation.promotion_page_config.input_tips4'
								)
							"
							autocomplete="off"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="$t('common.remark') + ':'"
						prop="remark"
						:rules="[
							{
								required: true,
								message: $t('common.please_enter'),
								trigger: 'blur'
							},
							{
								min: 2,
								max: 500,
								message: $t(
									'operation.promotion_page_config.input_tips5'
								),
								trigger: 'blur'
							}
						]"
					>
						<el-input
							v-model="dialogData.remark"
							:placeholder="
								$t(
									'operation.promotion_page_config.input_tips6'
								)
							"
							maxlength="500"
							show-word-limit
							clearable
							type="textarea"
							v-input="{ name: 'noEmpty' }"
						></el-input>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = false">
						{{ $t('common.cancel') }}
					</el-button>
					<el-button type="primary" @click="subAddOrEidt">
						{{ $t('common.save') }}
					</el-button>
				</div>
			</el-dialog>
		</div>
	</div>
</template>

<script>
import list from '@/mixins/list'
import Sortable from 'sortablejs'
import { routerNames } from '@/utils/consts'
import {
	promotionDel,
	promotionList,
	promotionPageAdd,
	promotionPageEdit
} from '@/api/operation'
import { mapGetters } from 'vuex'

export default {
	name: routerNames.promotionPageConfig,
	mixins: [list],
	data() {
		return {
			queryData: {
				merchantClientId: undefined
			},
			pageNum: 1,
			pageSize: 100,
			tableData: [],
			dialogVisible: false,
			merchantInfoA: {
				languages: 'zh_CN'
			},
			dialogData: {
				activityNameCn: '',
				activityNameEn: '',
				activityNameTh: '',
				activityNameVn: '',
				merchantId: '',
				remark: ''
			},
			addOrEdit: 0,
			rowData: null
		}
	},
	computed: {
		...mapGetters(['merchantInfo']),
		getMerchantInfo() {
			return this.merchantInfo
		},
		statusArr() {
			return this.globalDics.operateStatus || []
		},
		terminalTypeArr() {
			return [
				{
					code: '0',
					description: 'APP'
				}
			]
		}
	},
	mounted() {
		if (!this.$store.getters.isZk) {
			this.queryData.merchantClientId = this.$store.getters.merchantInfo.id
		}
		this.loadData()
		this.setSort()
	},

	methods: {
		handleMerchantIdChange() {
			this.dialogData.activityNameCn = ''
			this.dialogData.activityNameEn = ''
			this.dialogData.activityNameTh = ''
			this.dialogData.activityNameVn = ''
			this.$refs.dialogForm.clearValidate([
				'activityNameCn',
				'activityNameEn',
				'activityNameTh',
				'activityNameVn'
			])
		},
		filterLanguages(lang) {
			return this.merchantInfoA?.languages
				? this.merchantInfoA?.languages?.indexOf(lang) !== -1
				: false
		},
		reset() {
			this.$refs.searchForm.resetFields()
			this.loadData()
		},
		loadData() {
			if (!this.queryData.merchantClientId) {
				this.loading = true
				this.tableData = []
				setTimeout(() => (this.loading = false), 500)
				return
			}
			this.loading = true
			const params = {
				...this.queryData
			}
			promotionList(params)
				.then((res) => {
					if (res?.code === 200) {
						this.tableData = res.data || []
					}
					this.loading = false
				})
				.catch(() => {
					this.loading = false
				})
		},
		changeSwitch(val) {
			this.$api
				.getOperateActivityConfiTabUpdateStatus({
					id: val.id,
					activityStatus: val.activityStatus ? 0 : 1
				})
				.then(() => {
					this.loading = false
					this.$message.success(this.$t('common.modify_success'))
					this.loadData()
				})
				.catch(() => (this.loading = false))
		},
		addOrEditButton(flag, val) {
			this.addOrEdit = flag
			if (flag === 0) {
				this.rowData = null
				this.dialogVisible = true

				this.dialogData.activityNameCn = undefined
				this.dialogData.activityNameEn = undefined
				this.dialogData.activityNameTh = undefined
				this.dialogData.activityNameVn = undefined
				this.dialogData.remark = undefined

				if (!this.$store.getters.isZk) {
					this.dialogData.merchantId = this.$store.getters.merchantInfo.id
				} else {
					this.dialogData.merchantId = undefined
				}
			} else {
				this.rowData = { ...val }
				this.dialogVisible = true
				this.$nextTick(() => {
					for (const k in this.dialogData) {
						this.dialogData[k] = val[k]
					}
				})
			}
		},
		onDialogClose() {
			this.$refs.dialogForm.resetFields()
		},
		deleteButton(val) {
			const data = {}
			data.id = val.id
			this.$confirm(
				`<strong>${this.$t('operation.delete_tips')}?</strong>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					promotionDel(data).then((res) => {
						if (res?.code === 200) {
							this.$message.success(
								this.$t('common.delete_success')
							)
							this.loadData()
						}
					})
				})
				.catch(() => {})
		},
		subAddOrEidt() {
			this.$refs.dialogForm.validate((valid) => {
				const params = { ...this.dialogData }
				const sub = this.rowData ? promotionPageEdit : promotionPageAdd
				if (this.rowData) {
					params.id = this.rowData.id
				}
				if (valid) {
					sub(params).then((res) => {
						if (res?.code === 200) {
							this.$message.success(
								this.$t('common.action_success')
							)
							this.loadData()
							this.dialogVisible = false
						} else {
							this.$message.error(res.msg)
						}
					})
				}
			})
		},
		setSort() {
			const tbody = document.querySelector(
				'.el-table__body-wrapper tbody'
			)
			const _this = this
			Sortable.create(tbody, {
				animation: 150,
				ghostClass: 'ghost',
				onEnd({ newIndex, oldIndex }) {
					const currRow = _this.tableData.splice(oldIndex, 1)[0]
					_this.tableData.splice(newIndex, 0, currRow)
					const list = []
					for (let i = 0; i < _this.tableData.length; i++) {
						const ele = _this.tableData[i]
						list.push({ sort: i + 1, id: ele.id })
					}
					_this.$api
						.getOperateActivityConfiTabUpdateSort({ list })
						.then((res) => {
							if (res.code === 200) {
								_this.$message.success(
									_this.$t('common.action_success')
								)
								_this.loadData()
							}
						})
				}
			})
		}
	}
}
</script>
<style lang="scss" scoped>
.dialogStyle {
	::v-deep .el-dialog__header {
		color: #5c5c5c;
		font-weight: 700;
	}
	::v-deep .el-dialog__body {
		padding: 0;
		form {
			padding: 0 30px;
		}
	}
	::v-deep .el-dialog__footer {
		text-align: center;
	}
}
::v-deep .ghost {
	opacity: 0.5;
	color: #fff;
	background: #b9e0f7;
}
</style>
